import React, { useRef, useState, useEffect } from 'react';
import { useLocation } from 'react-router';
import LRUCache from '@/app/common/dataStructure/LRUCache';
import { useOutlet } from 'react-router-dom';

function KeepAlive() {
  const [active, setActive] = useState('');
  const components = useRef<LRUCache>(new LRUCache(30));
  const containerRef = useRef<HTMLDivElement>();
  const outlet = useOutlet();
  const { pathname, search, state } = useLocation();
  const key = pathname;

  useEffect(() => {
    setActive(key);
  }, [key]);

  useEffect(() => {
    if (outlet !== null && outlet && !components.current.has(key)) {
      components.current.put(key, outlet);
    } else {
      components.current.get(key);
    }
  }, [key]);

  const comps = components.current.toArr();

  return (
    <div className="keep-alive" style={{ height: '100%', width: '100%' }} ref={containerRef}>
      {comps.length > 0
        ? comps.map(([key, comp]) => {
            return (
              <div
                style={{
                  display: active === key ? 'block' : 'none',
                  height: '100%',
                  width: '100%',
                }}
                key={key}
                id={key}
              >
                {comp || outlet}
              </div>
            );
          })
        : outlet}
    </div>
  );
}

export default React.memo(KeepAlive);
